<template>
  <div class="app-container">
    <a-row :gutter="20">
      <!--部门数据-->
      <a-col :span="4">
        <div class="head-container">
          <a-input-search
              style="margin-bottom: 8px; max-width: 240px"
              placeholder="请输入部门名称"
              v-model="deptName"
          />
        </div>
        <div class="head-container">
          <a-tree
              :data="treeData"
              :fieldNames="{ title: 'label', children: 'children' }"
              @select="handleNodeClick"
          >
            <template #title="nodeData">
              <template v-if="index = getMatchIndex(nodeData?.label), index < 0">{{ nodeData?.label }}</template>
              <span v-else>
                {{ nodeData?.label?.substr(0, index) }}
                <span style="color: var(--color-primary-light-4);">
                  {{ nodeData?.label?.substr(index, deptName.length) }}
                </span>
                {{ nodeData?.label?.substr(index + deptName.length) }}
              </span>
            </template>
          </a-tree>
        </div>
      </a-col>
      <!--用户数据-->
      <a-col :span="20">
        <!--头部搜索-->
        <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch" label-width="68px">
          <a-form-item label="用户名称" field="userName">
            <a-input
                size="small"
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </a-form-item>
          <a-form-item label="手机号码" field="phonenumber">
            <a-input
                size="small"
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </a-form-item>
          <a-form-item label="状态" field="status">
            <a-select
                v-model="queryParams.status"
                size="small"
                placeholder="用户状态"
                clearable
                style="width: 240px"
            >
              <a-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </a-select>
          </a-form-item>
          <a-form-item label="创建时间" style="width: 308px;">
            <a-range-picker
                size="small"
                v-model="dateRange"
            ></a-range-picker>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleQuery" size="small" class="button-margin-right">
              <template #icon>
                <icon-search/>
              </template>
              搜索
            </a-button>
            <a-button @click="resetQuery" size="small">
              <template #icon>
                <icon-loop/>
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
        <!--操作-->
        <a-row :gutter="10" class="mb8">
          <a-col :span="1.5">
            <a-button
                size="small"
                type="primary"
                @click="handleAdd"
                v-hasPermi="['system:user:add']"
            >
              <template #icon>
                <icon-plus/>
              </template>
              新增
            </a-button>
          </a-col>
          <a-col :span="1.5">
            <a-button
                type="primary"
                status="success"
                size="small"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:user:edit']"
            >
              <template #icon>
                <icon-edit/>
              </template>
              修改
            </a-button>
          </a-col>
          <a-col :span="1.5">
            <a-button
                type="primary"
                status="danger"
                size="small"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['system:user:remove']"
            >
              <template #icon>
                <icon-delete/>
              </template>
              删除
            </a-button>
          </a-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </a-row>
        <!--表格-->
        <a-table row-key="userId" :pagination="false" v-loading="loading" :data="userList"
                 :row-selection="userRowSelection" v-model:selectedKeys="selectedUserIds">
          <template #columns>
            <a-table-column title="用户编号" align="center" key="userId" data-index="userId" v-if="columns[0].visible"/>
            <a-table-column title="用户名称" align="center" key="userName" data-index="userName" v-if="columns[1].visible"
                            :show-overflow-tooltip="true"/>
            <a-table-column title="用户昵称" align="center" key="nickName" data-index="nickName" v-if="columns[2].visible"
                            :show-overflow-tooltip="true"/>
            <a-table-column title="部门" align="center" key="deptName" data-index="dept.deptName"
                            v-if="columns[3].visible"
                            :show-overflow-tooltip="true"/>
            <a-table-column title="手机号码" align="center" key="phonenumber" data-index="phonenumber"
                            v-if="columns[4].visible"
                            width="130"/>
            <a-table-column title="状态" align="center" key="status" v-if="columns[5].visible">
              <template #cell="{ record }">
                <a-switch
                    v-model="record.status"
                    checked-value="0"
                    unchecked-value="1"
                    @change="handleStatusChange(record)"
                ></a-switch>
              </template>
            </a-table-column>
            <a-table-column title="创建时间" align="center" data-index="createTime" v-if="columns[6].visible" width="180">
              <template #cell="{ record }">
                <span>{{ parseTime(record.createTime) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="操作" align="center" width="180" class-name="small-padding fixed-width">
              <template #cell="{ record }">
                <a-tooltip mini content="修改" position="top" v-if="record.userId !== 1">
                  <a-button
                      type="text"
                      class="button-text-padding"
                      @click="handleUpdate(record)"
                      v-hasPermi="['system:user:edit']"
                  >
                    <icon-edit/>
                  </a-button>
                </a-tooltip>
                <a-tooltip mini content="删除" position="top" v-if="record.userId !== 1">
                  <a-button
                      type="text"
                      class="button-text-padding"
                      @click="handleDelete(record)"
                      v-hasPermi="['system:user:remove']"
                  >
                    <icon-delete/>
                  </a-button>
                </a-tooltip>
                <a-tooltip mini content="重置密码" position="top" v-if="record.userId !== 1">
                  <a-button
                      type="text"
                      class="button-text-padding"
                      @click="handleResetPwd(record)"
                      v-hasPermi="['system:user:resetPwd']"
                  >
                    <icon-lock/>
                  </a-button>
                </a-tooltip>
                <a-tooltip mini content="分配角色" position="top" v-if="record.userId !== 1">
                  <a-button
                      type="text"
                      class="button-text-padding"
                      @click="handleAuthRole(record)"
                      v-hasPermi="['system:user:edit']"
                  >
                    <icon-check-circle/>
                  </a-button>
                </a-tooltip>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </a-col>
    </a-row>

    <!-- 添加或修改用户配置对话框 -->
    <a-modal v-model:visible="open" width="600px" title-align="start">
      <template #title>
        {{ title }}
      </template>
      <a-form :model="form" :rules="rules" ref="userRef" auto-label-width>
        <a-row>
          <a-col :span="12">
            <a-form-item label="用户昵称" field="nickName">
              <a-input size="small" v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="归属部门" field="deptId">
              <a-tree-select
                  v-model="form.deptId"
                  :data="deptOptions"
                  :fieldNames="{ key: 'id', title: 'label', children: 'children' }"
                  placeholder="请选择归属部门"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="手机号码" field="phonenumber">
              <a-input size="small" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" field="email">
              <a-input size="small" v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item v-if="form.userId == undefined" label="用户名称" field="userName">
              <a-input size="small" v-model="form.userName" placeholder="请输入用户名称" maxlength="30"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item v-if="form.userId == undefined" label="用户密码" field="password">
              <a-input-password size="small" v-model="form.password" placeholder="请输入用户密码" maxlength="20" allow-clear/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="用户性别">
              <a-select size="small" v-model="form.sex" placeholder="请选择">
                <a-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态">
              <a-radio-group v-model="form.status">
                <a-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :value="dict.value"
                >{{ dict.label }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="片区" field="areaId">
              <a-select v-model="form.areaId" placeholder="请选择">
                <a-option
                    v-for="dict in bis_area_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色">
              <a-select v-model="form.roleIds" multiple :max-tag-count="1" placeholder="请选择">
                <a-option
                    v-for="item in roleOptions"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId"
                    :disabled="item.status == 1"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="备注">
              <a-input v-model="form.remark" type="textarea" placeholder="请输入内容"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button size="small" class="button-margin-right" type="primary" @click="submitForm">确 定</a-button>
          <a-button size="small" @click="cancel">取 消</a-button>
        </div>
      </template>
    </a-modal>

    <!-- 用户导入对话框 -->
    <a-modal v-model:visible="upload.open" width="400px" title-align="start">
      <template #title>
        {{ upload.title }}
      </template>
      <a-upload
          draggable
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :progress="handleFileUploadProgress"
          :success="handleFileSuccess"
          :auto-upload="false"
      >
        <template #upload-button>
          <div
              style="
        background-color: #ffffff;
        color: var(--color-text-1);
        border: 1px dashed #409eff;
        height: 160px;
        width: 360px;
        border-radius: 8px;
        line-height: 160px;
        text-align: center;"
          >
            <div>
              将文件拖到此处，或
              <span style="color: #409eff">点击上传</span>
            </div>
          </div>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <a-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <a-link style="font-size:12px;vertical-align: baseline;"
                    @click.stop="importTemplate">下载模板
            </a-link>
          </div>
        </template>
      </a-upload>
      <template #footer>
        <div class="dialog-footer">
          <a-button size="small" class="button-margin-right" type="primary" @click="submitFileForm">确 定</a-button>
          <a-button size="small" @click="upload.open = false">取 消</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="User">
import {getToken} from "@/utils/auth";
import {treeselect} from "@/api/system/dept";
import {changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser} from "@/api/system/user";
import {useRouter} from "vue-router";
import {getCurrentInstance, computed, reactive, ref} from "vue";

const router = useRouter();
const {proxy} = getCurrentInstance();
const {sys_normal_disable, sys_user_sex} = proxy.useDict("sys_normal_disable", "sys_user_sex");
const { bis_area_type } = proxy.useDict("bis_area_type");

const deptName = ref("");
const deptOptions = ref(undefined);
/*** 部门树过滤 */
const treeData = computed(() => {
  if (!deptName.value) return deptOptions.value;
  return searchData(deptName.value);
})

function searchData(keyword) {
  const loop = (data) => {
    const result = [];
    data.forEach(item => {
      if (item.label.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({...item});
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          })
        }
      }
    })
    return result;
  }

  return loop(deptOptions.value);
}

function getMatchIndex(label) {
  if (!deptName.value) return -1;
  return label.toLowerCase().indexOf(deptName.value.toLowerCase());
}

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});
// 列显隐信息
const columns = ref([
  {key: 0, label: `用户编号`, visible: true, dataIndex: 'userId'},
  {key: 1, label: `用户名称`, visible: true, dataIndex: 'userName'},
  {key: 2, label: `用户昵称`, visible: true, dataIndex: 'nickName'},
  {key: 3, label: `部门`, visible: true, dataIndex: 'deptName'},
  {key: 4, label: `手机号码`, visible: true, dataIndex: 'phonenumber'},
  {key: 5, label: `状态`, visible: true, dataIndex: 'status'},
  {key: 6, label: `创建时间`, visible: true, dataIndex: 'createTime'}
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },
  rules: {
    userName: [{required: true, message: "用户名称不能为空", trigger: "blur"}, {
      min: 2,
      max: 20,
      message: "用户名称长度必须介于 2 和 20 之间",
      trigger: "blur"
    }],
    nickName: [{required: true, message: "用户昵称不能为空", trigger: "blur"}],
    password: [{required: true, message: "用户密码不能为空", trigger: "blur"}, {
      min: 5,
      max: 20,
      message: "用户密码长度必须介于 5 和 20 之间",
      trigger: "blur"
    }],
    email: [{type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}],
    phonenumber: [{pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}]
  }
});

const {queryParams, form, rules} = toRefs(data);


/** 查询部门下拉树结构 */
function getTreeselect() {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
}

/** 查询用户列表 */
function getList() {
  selectedUserIds.value = []
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });
}

/** 节点单击事件 */
function handleNodeClick(selectedKeys, data) {
  console.log(data.node)
  queryParams.value.deptId = data.node.id;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || selectedUserIds.value;
  proxy.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds);
  }).then(() => {
    getList();
    proxy.$message.success("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/user/export", {
    ...queryParams.value,
  }, `user_${new Date().getTime()}.xlsx`);
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status);
  }).then(() => {
    proxy.$message.success(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
}

/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
  }).then(({value}) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$message.success("修改成功，新密码是：" + value);
    });
  }).catch(() => {
  });
}

/** 开启表格多选  */
const selectedUserIds = ref([]);
const userRowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});
// 修改按钮生效
const single = computed(() => {
  return selectedUserIds.value.length !== 1
});
// 删除按钮生效
const multiple = computed(() => {
  return !selectedUserIds.value.length
});
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/user/importTemplate", {}, `user_template_${new Date().getTime()}.xlsx`);
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 初始化部门数据 */
function initTreeData() {
  // 判断部门的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    treeselect().then(response => {
      deptOptions.value = response.data;
    });
  }
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  proxy.resetForm("userRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  initTreeData();
  getUser().then(response => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  initTreeData();
  const userId = row.userId || selectedUserIds.value[0];
  getUser(userId).then(response => {
    form.value = response.data;
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    form.value.postIds = response.postIds;
    form.value.roleIds = response.roleIds;
    open.value = true;
    title.value = "修改用户";
    form.password = "";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (!valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then(response => {
          proxy.$message.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then(response => {
          proxy.$message.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

getTreeselect();
getList();
</script>
